#define _LIBC
#include <stdio.h>
#include <string.h>
#include "system.h"


FILE *__stdio_head;

FILE *stdin;
FILE *stdout;
FILE *stderr;

FILE uart_out;
FILE uart_in;

//typedef __ssize_t __io_write_fn __P ((__ptr_t __cookie, __const char *__buf, size_t __n));
static ssize_t pwrite(void * cookie, const char *buf, size_t n)
{
  for(size_t i=0;i<n;i++){
    uart_write(buf[i]);
  }
  return n;
}

//typedef __ssize_t __io_read_fn __P ((__ptr_t __cookie, char *__buf, size_t __nbytes));
static ssize_t pread(void * cookie, char *buf, size_t n)
{
  for(size_t i=0;i<n;i++){
    buf[i] = uart_read();
  }
  return n;
}


void initStdio(){
  memset((void*)&uart_out, 0, sizeof(FILE));
  uart_out.__magic = _IOMAGIC;
  uart_out.__mode.__write = 1;
  uart_out.__cookie = 0;
  uart_out.__room_funcs = __default_room_functions;
  uart_out.__io_funcs.__write = pwrite;
  uart_out.__seen = 1;
  uart_out.__userbuf = 1;
  stdout = &uart_out;

  memset((void*)&uart_in, 0, sizeof(FILE));
  uart_in.__magic = _IOMAGIC;
  uart_in.__mode.__read = 1;
  uart_in.__cookie = 0;
  uart_in.__room_funcs = __default_room_functions;
  uart_in.__io_funcs.__read = pread;
  uart_in.__seen = 1;
  uart_in.__userbuf = 1;
  stdin = &uart_in;

}

